package isquirrel.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static SessionFactory sessionFactory;
	private static SessionFactory testSessionFactory;
   
	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().buildSessionFactory();
		}
		catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	private static SessionFactory buildTestSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new Configuration().configure().				
				setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/isquirrel_test_db").
				setProperty("hibernate.hbm2ddl.auto", "create").
				buildSessionFactory();
		}
		catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public static SessionFactory getSessionFactory() {
		if (sessionFactory == null) {
			sessionFactory = buildSessionFactory();
		}
		return sessionFactory;
	}
	
	public static void useTestDB() {
		if (testSessionFactory == null) {
			testSessionFactory = buildTestSessionFactory();
		}
		sessionFactory = testSessionFactory;
	}
	
	public static Session getSession() {	
		return getSessionFactory().getCurrentSession();
	}
	
	public static void beginTransaction() {
		getSessionFactory().getCurrentSession().beginTransaction();
	}
	
	public static void commit() {
		getSessionFactory().getCurrentSession().getTransaction().commit();
	}
	
	public static void rollback() {
		getSessionFactory().getCurrentSession().getTransaction().rollback();
	}
}